package com.example.fridaykt.config

import cn.dev33.satoken.context.SaHolder
import cn.dev33.satoken.filter.SaFilterAuthStrategy
import cn.dev33.satoken.filter.SaFilterErrorStrategy
import cn.dev33.satoken.filter.SaServletFilter
import cn.dev33.satoken.`fun`.SaParamFunction
import cn.dev33.satoken.jwt.StpLogicJwtForSimple
import cn.dev33.satoken.router.SaHttpMethod
import cn.dev33.satoken.router.SaRouter
import cn.dev33.satoken.router.SaRouterStaff
import cn.dev33.satoken.stp.StpLogic
import com.example.fridaykt.common.result.R
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

@Configuration
class SatokenConfig : WebMvcConfigurer {
    @get:Bean
    val stpLogicJwt: StpLogic
        // Sa-Token 整合 jwt (Style模式)
        get() = StpLogicJwtForSimple()


    @get:Bean
    val saServletFilter: SaServletFilter
        /**
         * 注册 [Sa-Token全局过滤器]
         */
        get() = SaServletFilter()

            .addInclude("/**")
            .addExclude("/user/login")
            .addExclude("/user/info")
            .addExclude("/u/login")
            .addExclude("/swagger-ui.html")
            .addExclude("/v2/**")
            .addExclude("/swagger-resources/**")
            .addExclude("/webjars/springfox-swagger-ui")
            .addExclude("/webjars/springfox-swagger-ui/**")


            .setAuth(SaFilterAuthStrategy { obj: Any? -> })

            .setError(SaFilterErrorStrategy { e: Throwable -> R.error(500, e.message) })

            .setBeforeAuth(SaFilterAuthStrategy { obj: Any? ->
                SaHolder.getResponse()
                    .setHeader("Access-Control-Allow-Origin", "*")
                    .setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE")
                    .setHeader("Access-Control-Max-Age", "3600")
                    .setHeader("Access-Control-Allow-Headers", "*")
                SaRouter.match(SaHttpMethod.OPTIONS)
                    .free(SaParamFunction<SaRouterStaff> { r: SaRouterStaff? -> println("--------OPTIONS预检请求，不做处理") })
                    .back()
            })
}
